<?php
namespace app\controllers;


use app\controllers\common\BaseController;
use app\models\Teacher;
use app\service\UrlService;
use app\models\User;
use app\models\SignUser;
use app\models\Role;
use app\models\UserRole;
use app\models\Visitlog;
use yii\web\Controller;
use yii\data\Pagination;
use app\models\TmpStudent;

use yii;
class UserController extends BaseController
{
    //学生角色的id ，这里设置的是：在注册页面注册的用户的默认角色的角色id
    public $student_role_id = 2;
    //老师角色的id ，
    public $teacher_role_id = 1;

	public function actionIndex(){
		/* 查询所有用户 */
		$user_list = User::find()->where(['status'=>1])->orderBy(['id'=>SORT_DESC])->all();
		$set_flag = true;
		return $this->render('index',[
			'list'=>$user_list,
			'set_flag'=>$set_flag
		]);
	}
	public function actionSet(){
		if(yii::$app->request->isGet){
			$id = $this->get('id',0);
			$user_info = User::find()->where(['id'=>$id])->one();
			if(!$user_info){
				return $this->render([],'用户不存在',-1);
			}
			//获取用户的角色
			$user_role = UserRole::find()->where(['uid'=>$id])->asArray()->select('rid')->column();
			
			/* 获取全部角色 */
			$roles = Role::find()->where(['status'=>1])->all();
			if(!$roles){
				return $this->render([],'没有角色，请联系管理员',-1);	
			}

			return $this->render('set',[
				'info'=>$user_info,
				'role_list'=>$roles,
				'related_role_ids'=>$user_role,
			]);
		}
		//这里开始时post请求了

		$id = $this->post('id',0);
		$email = $this->post('email','');
		$role_ids = $this->post('role_ids',[]);
		$name = $this->post('name','');
		if(!$id){
			return $this->renderJSON([],'用户不存在',-1);
		}
		if(!preg_match("/^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/",$email)){
			return $this->renderJSON([],'请填写正确的邮箱地址',-1);
		}
		if(mb_strlen($name,'utf-8')<1 || mb_strlen($name,'utf-8')>10){
			return $this->renderJSON([],'用户名不合法',-1);
		}

		//获取当前用户的角色列表的id
		$user_roles = UserRole::find()->where(['uid'=>$id])->select('rid')->asArray()->column();

		//获取全部角色列表
		$roles = Role::find()->where(['status'=>1])->all();


		// 取post数据和角色但是的角色集合的差集， 来添加
		$add_list = array_diff($role_ids,$user_roles);

		if($add_list){
			foreach ($add_list as $key => $value) {
				$user_role_model = new UserRole();
				$user_role_model->rid = $value;
				$user_role_model->uid = $id;
				$user_role_model->create_time = date('Y-m-d H:i:s');
				$user_role_model->save(0);
			}
		}

		// 取角色当前的角色集合和post数据的差集， 来添加
		$del_list = array_diff($user_roles,$role_ids);
		if($del_list){
			UserRole::deleteAll(['uid'=>$id,'rid'=>$del_list]);
		}

		return $this->renderJSON([],'操作成功',200);
	}
	//用户登录页面
	public function actionLogin(){
        $model = new User();
        //提交post表单过来时:
        if(yii::$app->getRequest()->isPost && $model->load($this->post(null))){
            $email = $model->email;
            $password = $model->password;
            $info = User::find()->where(['email'=>$email])->asArray()->one();
            $is_login = yii::$app->getSecurity()->validatePassword($password,$info['password']);
           if(!$is_login){// 密码验证失败
               return $this->renderPartial("login",['model'=>$model,'message'=>'邮箱或密码错误']);
           }
            unset($info['password']);

           $user_info = $info;
            //  设置登录态

            $this->createLoginStatues($user_info);
           return $this->redirect('/');
        }
//        返回登录视图
		return $this->renderPartial("login",['model'=>$model,'message'=>'']);
	}

	public function actionRegister(){
	    $user = new User();
	    if(\yii::$app->request->isPost){
	        if(//加载数据并验证
	            !$user->load($this->post(null))
                || !$user->validate()
            ){return 0;}
	        //验证邮箱是否存在
            $exists = $user::findOne(['email'=>$user->email]);
//	        如果存在
	        if($exists){return $this->renderPartial(UrlService::BuildUrl('user/register'),['model'=>$user,'message'=>'邮箱已被注册']);}
            $passwd = yii::$app->getSecurity()->generatePasswordHash($user->password);
            $user->password = $passwd;
            $user->status = 1;
            $user->is_admin = 0;
            if($user->save()){
                //添加学生身份
                //   注意！！！这里的 student_role_id 学生角色id是手动添加的，如果修改了，得改！！
                $this->addRole($user->id,$this->student_role_id);
//                保存到临时表等待分配班级
                $tmp = new TmpStudent();
                $tmp->name = $user->name;
                $tmp->email = $user->email;
                $tmp->student_id = $user->id;
                $tmp->save();
               return $this->redirect(UrlService::BuildUrl('user/login'));
           }


        }
	    return $this->renderPartial(UrlService::BuildUrl('user/register'),['message'=>'123','model'=>$user]);
    }

	//   伪登录
	public function actionVlogin($uid){
		$reback_url = UrlService::BuildUrl('/');
		$uid = $this->get('uid',0);
		if(!$uid){
			return $this->redirect( $reback_url);
		}
		$user_info = User::find()->where(['id'=>$uid])->one();
		if(!$user_info){
			return $this->redirect( $reback_url );
		}
        unset($user_info['password']);

		//  设置登录态
		$this->createLoginStatues($user_info);

		return $this->redirect($reback_url);

	}

	/*
		添加用户
		如果用set，没有用户就穿件，有点危险；因此另外创建一个方法
	*/
	public function actionAdd(){
		if(yii::$app->request->isGet){
			/* 获取全部角色 */
			$roles = Role::find()->where(['status'=>1])->all();
			if(!$roles){
				return $this->render([],'没有角色，请联系管理员',-1);	
			}
			$user_info = [];
			$user_role = [];
			return $this->render('add',[
				'info'=>$user_info,
				'role_list'=>$roles,
				'related_role_ids'=>$user_role,
			]);
		}
		//  执行添加
		$email = $this->post('email','');
		$role_ids = $this->post('role_ids',[]);
		$name = $this->post('name','');
		$password = $this->post('password','');
		if(!preg_match("/^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/",$email)){
			return $this->renderJSON([],'请填写正确的邮箱地址',-1);
		}
		if(mb_strlen($name,'utf-8')<1 || mb_strlen($name,'utf-8')>10){
			return $this->renderJSON([],'用户名不合法',-1);
		}
        if(mb_strlen($password,'utf-8')<5 || mb_strlen($password,'utf-8')>32){
            return $this->renderJSON([],'密码长度不合法',-1);
        }
        /* 添加用户*/
        $now_date = date('Y-m-d H:i:s');
        $user_model = new User();
        $user_model->email = $email;
        $user_model->name = $name;
        if($password){
            $user_model->password = yii::$app->getSecurity()->generatePasswordHash($password);
        }
        $user_model->create_time = $now_date;
        $user_model->save();
        // 获取 添加的id
        $uid = $user_model->attributes['id'];
        if($role_ids && in_array($this->teacher_role_id,$role_ids)){
            $addres = $this->addTeacher($uid,$user_model->name);
            if($addres==500){
                $this->renderJSON([],'params not be null',500);
            }
        }
//            添加用户到老师表里
//        如果有老师的生份
        /* 如果有权限，添加权限 */
		if($role_ids){
			foreach ($role_ids as $key => $value) {
				$user_role_model = new UserRole();
				$user_role_model->rid = $value;
				$user_role_model->uid = $uid;
				$user_role_model->create_time = $now_date;
				$user_role_model->save();
			}
		}

		return $this->renderJSON([],'操作成功',200);
	}

	/*添加老师
	 *
	 * */
	public function addTeacher($tid,$name){
	    $exists = Teacher::findOne(['teacher'=>$tid]);
        if(empty($tid)||empty($name)){
//	        参数不能为空
            return 500;
        }
        if($exists){
            return 501;
        }
        $teacher_model = new Teacher();
	    $teacher_model->teacher = $tid;
	    $teacher_model->name = $name;
	    //如果保存失败，返回false
        if(!$teacher_model->save()){
            return 500;
        }
        return 200;

    }

	/*
		用户访问记录
		分页
		麻麻再也不用担心你做坏事了
	*/
	public function actionUserlog(){
			$visitmodel = Visitlog::find();
			$pages = new Pagination(['totalCount'=>$visitmodel->count()]);
			$result = $visitmodel->offset($pages->offset)->limit($pages->limit)->orderBy(['id'=>SORT_DESC])->all();
		
			return $this->render('userlog',[
				'visitlog'=>$result,
				'page'=>$pages,
			]);
			
	}

}